<template>
	<view>
		<view class="topnav">
			<uni-nav-bar :fixed="true" :title="item.title" leftIcon="left" @clickLeft="clickLeft"></uni-nav-bar>
		</view>
		<view class="baseInfoBox">
			<view class="baseInfo">
				<view class="limg">
					<image style="width: 200rpx;height: 300rpx;" :src="item.cover"></image>
				</view>
				<view class="rbaseInfo">
					<view class="titleAndAuthor">
						<view class="">
							<view class="title">
								<text>{{item.title}} <small style="font-size: 20rpx;">{{item.fictionType}}</small></text>
							</view>
							<view class="author">
								<view class="">
									{{item.author}}
								</view>
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								<view class="">
									<text>{{item.updateTime.substring(0,10)}}</text>
								</view>
							</view>
						</view>
						<view class="bookShelf" @click="addBookShelf">
							<text>收藏</text> 
						</view>
					</view>
					<view class="descs">
						{{item.descs}}
					</view>
				</view>
			</view>
		</view>
		<view class="outherInfo">
			<view class="chapterCache">
				<view class="">
					共{{chapterList.length}}章
					&nbsp;&nbsp;&nbsp; <text @click="updateChapter" style="padding: 2rpx 10rpx;border: 1px solid #dfdfdf;border-radius: 5px;">更新</text>
				</view>
				<view class="">
					<!-- <span class="iconfont icon-downarrow"></span> -->
					<text @click="cacheChapterList">
						<span class="iconfont icon-yunhuancun" style="font-size: 50rpx;"></span>
					</text>
				</view>
			</view>
			<view class="">
				
			</view>
		</view>
		<view>
			<view class="">
				最新章节：
			</view>
			<view style="text-indent: 1em;font-size: 30rpx;color: #ff685d;"  @click="goPage(newChapter)">
				<text >
					{{newChapter.title}}
				</text>
			</view>
		</view>
		<view class="lastReadBox">
			<view class="lastRead">
				<view class="">
					上次读: 
				</view>
				<view style="text-indent: 1em;font-size: 30rpx;color: #ff685d;"  @click="goPage(lastReadChapter)">
					<text>{{lastReadChapter.title}}</text>
				</view>
			</view>
			<view class="allChapter">
				<text @click="openDrawer">全部章节</text>
			</view>
		</view>
		<view class="listBox">
			<uni-list>
				<uni-list-item :clickable="true" @click="goPage(item)" name="item.title" v-for="(item,index) in dataList" 
				 :key="index" :title="item.title" ></uni-list-item>
			</uni-list>
			<uni-load-more :status="moreMsg"></uni-load-more>
		</view>
		<view class="unidrawerBox">
			<uni-drawer ref="showRight" mode="right">
				<scroll-view style="height: 100%;" scroll-y="true" :show-scrollbar="true">
					<view class="chapter"  @click="goPage(item)" v-for="(item,index) in chapterList" :key="index">{{item.title}}</view>
				</scroll-view>
			</uni-drawer>
		</view>
	</view>
</template>

<script>
	import * as DB from "@/compoment/DB.js"
	export default {
		data() {
			return {
				lastReadChapter:{},
				item:{},
				dataList:[],
				total:0,
				chapterList:[],
				moreMsg:"more",
				start:30,
				end:60,
				sliceChapterList:[],
				newChapter:{},
				errorNum:0
			}
		},
		onLoad(option) {
			try {
			    this.item = JSON.parse(option.item)
				this.loadChapters()
				this.getLastReadChapter()
				this.setReadBooks()
			}
			catch(err) {
				uni.reLaunch({
					url:"/pages/index/index"
				})
			}			
		},
		onPullDownRefresh() {
			this.loadChapters()
			this.getLastReadChapter()
		},
		onReachBottom() {
			this.spliceChapters()
		},
		onShow() {
			this.getLastReadChapter()
		},
		methods: {
			// 更新章节内容
			updateChapter(){
				// 请求数据
				//数据对比，
				//有更新删除重新添加
				//没更新不变化
				uni.request({
				 	url: `http://api.pingcc.cn/fictionChapter/search/${this.item.fictionId}`,
				 	method: "GET",
				 	success: ({
				 		data
				 	}) => {
						let chapterList = data.data.chapterList
						this.putChapters(chapterList,this.item.fictionId)
						DB.findCount(DB.config.tables.uu_bookChapter,{"fictionId":this.item.fictionId}).then((res)=>{
							if(res[0].count == chapterList.length){
								uni.showToast({
									icon:"none",
									title:"无更新"
								})
							}else{
								DB.remove(DB.config.tables.uu_bookChapter,{"fictionId":this.item.fictionId}).then(()=>{
									console.log(" remove")
									if(data.data.chapterList){
										this.total = data.data.chapterList.length
										this.moreMsg = data.data.chapterList.length<=30?"no-more":"more"
										this.dataList = data.data.chapterList.splice(0,30)
										this.chapterList = this.dataList.concat(data.data.chapterList)
										this.newChapter = this.chapterList[data.count-1]
										this.sliceChaptersList(this.chapterList)
										this.addBookChapter(this.chapterList)
									}else{
										this.moreMsg="no-more"
									}
									uni.showToast({
										icon:"none",
										title:"更新成功"
									})
								})
							}
						})
				 	},
					fail() {
				 		if(this.errorNum>=3){
				 			this.moreMsg="no-more"
				 			return false
				 		}
				 		this.loadChapters()
				 	},
				 })
			},
			sliceChaptersList(chapters){
				let sliceNum = Math.ceil(chapters.length/30)
				let start =0,end=30;
				for(let i=0;i<sliceNum;i++){
					this.sliceChapterList.push(chapters.slice(start,end))
					start+=30,end+=30;
				}
			},
			setReadBooks(){
				let historyBox = uni.getStorageSync("book")
				if(!historyBox){
					historyBox =[]
					historyBox.push(this.item)
				}else{
					let flag =true
					historyBox.forEach(book=>{if(book.fictionId == this.item.fictionId){flag = false}})
					if(flag)historyBox.push(this.item)
				}
				uni.setStorageSync("book",historyBox);
			},
			getLastReadChapter(){
				let obj = uni.getStorageSync(this.item.fictionId)
				this.lastReadChapter =  obj
			},
			goPage(item){
				uni.navigateTo({
					url:`/pages/index/book/content/content?fictionId=${this.item.fictionId}&item=`+JSON.stringify(item)
				})
			},
			clickLeft(){
				uni.navigateBack()
			},
			openDrawer(){
				this.$refs.showRight.open();
			},
			loadChaptersHttp(){
				uni.request({
				 	url: `http://api.pingcc.cn/fictionChapter/search/${this.item.fictionId}`,
				 	method: "GET",
				 	success: ({
				 		data
				 	}) => {
				 		if(data.data.chapterList){
							this.total = data.data.chapterList.length
				 			this.moreMsg = data.data.chapterList.length<=30?"no-more":"more"
				 			this.dataList = data.data.chapterList.splice(0,30)
				 			this.chapterList = this.dataList.concat(data.data.chapterList)
				 			this.newChapter = this.chapterList[data.count-1]
				 			this.sliceChaptersList(this.chapterList)
				 			this.addBookChapter(this.chapterList)
				 		}else{
				 			this.moreMsg="no-more"
				 		}
				 	},
				 	fail() {
				 		if(this.errorNum>=3){
				 			this.moreMsg="no-more"
				 			return false
				 		}
				 		this.loadChapters()
				 	},
				 })
			},
			loadChapters(){
				this.moreMsg="loading"
				//查有没有数据
				DB.selectBookAll("uu_bookChapter",this.item.fictionId).then((res)=>{
					if(res.length==0){
						uni.request({
						 	url: `http://api.pingcc.cn/fictionChapter/search/${this.item.fictionId}`,
						 	method: "GET",
						 	success: ({
						 		data
						 	}) => {
						 		if(data.data.chapterList){
						 			this.moreMsg = data.data.chapterList.length<=30?"no-more":"more"
						 			this.dataList = data.data.chapterList.splice(0,30)
						 			this.chapterList = this.dataList.concat(data.data.chapterList)
						 			this.newChapter = this.chapterList[data.count-1]
						 			this.sliceChaptersList(this.chapterList)
						 			this.addBookChapter(this.chapterList)
									this.putChapters(this.chapterList,this.item.fictionId);
						 		}else{
						 			this.moreMsg="no-more"
						 		}
						 	},
						 	fail() {
						 		if(this.errorNum>=3){
						 			this.moreMsg="no-more"
						 			return false
						 		}
						 		this.loadChapters()
						 	},
						 })
					}else{
						this.dataList =res.splice(0,30)
						this.chapterList =  this.dataList.concat(res)
						this.newChapter = this.chapterList[this.chapterList.length-1]
						if(this.chapterList.length<=30){
							this.moreMsg="no-more"
						}else{
							this.moreMsg="more"
						}
						// 获取远端的总数比较数据库的总数，不一样表示有更新，有更新则更新数据库，没有更新则使用数据库数据
						// 只管历史和书架内容的主动更新
					}
				}).catch((res)=>{
					console.log(res,"异常")
					DB.openSqlite()
				})
				uni.stopPullDownRefresh()
			},
			spliceChapters(){
				let size=30
				let chaptersSplice = this.chapterList.slice(this.start,this.end)
				this.dataList.push(...chaptersSplice)
				this.start+=size
				this.end+=size
				if(chaptersSplice.length<=0){
					this.moreMsg="no-more"
				}
			},
			addBookShelf(){
				let open = DB.isOpen()
				if(open){
					DB.insert("uu_bookShelf",this.item).then((res)=>{
						console.log("新增数据成功");
					}).catch((res)=>{
						console.log("失败");
					})
				}
			},
			addBookChapter(chapterList){
				let fictionId = this.item.fictionId
				let tableName = "uu_bookChapter"
				chapterList.forEach((chapter)=>{
					let obj = {
						'fictionId':fictionId,
						'title':chapter.title,
						'chapterId':chapter.chapterId
					}
					DB.insert(tableName,obj)
				})
			},
			// 缓存所有章节
			cacheChapterList(){
				let chapterList = this.chapterList
				let num = 1
				chapterList.forEach(chapter=>{
					DB.findCount(DB.config.tables.uu_chapterContent,{"chapterId":chapter.chapterId}).then((res)=>{
						if(res.data>0){
							uni.showToast({
								title:"第"+num+"章"+chapter.title+"已缓存"
							})
							num++
						}else{
							uni.request({
								url: `http://api.pingcc.cn/fictionContent/search/${chapter.chapterId}`,
								method: "GET",
								success: ({
									data
								}) => {
									if(data.data){
										let chapterContent = data.data
										DB.insert(DB.config.tables.uu_chapterContent,{'chapterId':chapter.chapterId,"content":JSON.stringify(chapterContent) }).then(()=>{
											uni.showToast({
												title:"缓存成功,第"+num+"章"+chapter.title
											})
											num++
										}).catch((err)=>{
											console.log("失败",err)
										})
									}else{ 
										
									}
								}
							})
						}
					})
				})
			},
			putChapters(chapters,fictionId){
				uni.request({
					url:"http://192.168.205.104:8900/chapter/putChapters?fictionId="+fictionId,
					method:"POST",
					data:chapters,
					success: (res) => {
						console.log(res)
					}
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.baseInfoBox{
		margin-bottom: 20rpx;
		border-bottom: 1px solid #e5e5e5;
	}
	.baseInfo{
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		margin: 0px 10rpx;
		.rbaseInfo{
			margin-left: 10rpx;
			.titleAndAuthor{
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				.bookShelf{
					border: 1px solid #dadada;
					border-radius: 5px;
					padding: 5px 10px;
				}
				.bookShelf:active{
					background-color: #55ff7f;
				}
			}
			.author{
				font-size: 30rpx;
				font-weight: 380;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
			}
			.descs{
				font-size: 20rpx;
				font-weight: 300;
			}
		}
	}
	.chapterCache{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 0px 10rpx;
	}
	.lastReadBox{
		font-weight: 390;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}
	.allChapter{
		padding-right: 20rpx;
	}
	.listBox{
		margin-top: 20rpx;
	}
	.chapter{
		padding: 10px 20rpx;
	}
</style>